const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const session = require('express-session');
// const MemcachedStore = require('connect-memcached')(session);
const http = require('http');
const https = require('https');
const fs = require('fs')
const url = require('url');
const config = global.sysConfig = require('./server-app/config/sysConf.json');

//日志
const logMiddleWare = require('./server-app/logger');
const logger = require('./server-app/logger/logger');

// const interceptor = require('./app-filters/interceptor')
// const filterHeaders = require('./app-filters/filterHeaders')

const app = express();

// uncomment after placing your favicon in /public
app.use(express.static(path.join(__dirname, 'public')));
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(cookieParser());
app.use(session({
  secret: 'env_app',
  resave: false,
  saveUninitialized: false,
  // store: new MemcachedStore({
  //   prefix: "ult_sess_",
  //   hosts: config.session.host,
  //   maxKeySize: config.session.maxKeySize,
  //   poolSize: 20,
  //   cookie: {
  //     maxAge: 100000
  //   }
  // })
}))

// app.use(interceptor);
// app.use(filterHeaders);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false,
  limit: '100mb',
}));

app.use(logMiddleWare())

// 处理路由
app.use('/env', require('./server-app/routers'))

// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  if (!err || typeof err !== 'object') {
    err = new Error(err)
  }
  err.status = err.status || 500;
  if (req.path.indexOf(".") > -1) {
    res.sendStatus(200);
    return;
  }
  res.type("json").send(err)
});

/**
 * Get port from environment and store in Express.
 */

const port = config.port
app.set('port', port);
/**
 * Create HTTP server.
 */
const server = http.createServer(app).listen(port);
// const server = https.createServer({
//   key: fs.readFileSync('./httpskey/server.key'),
//   cert: fs.readFileSync('./httpskey/server.crt')
// }, app).listen(port);
/**
 * Listen on provided port, on all network interfaces.
 */
server.on('error', onError);
server.on('listening', onListening);

/**
 * Event listener for HTTP server "error" event.
 */
function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
    logger.error(error);
  }

  let bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      logger.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      logger.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}
/**
 * Event listener for HTTP server "listening" event.
 */
function onListening() {
  let addr = server.address();
  let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
  logger.info('Listening on ' + bind);
}